package com.byl.sdk.utils;

import com.byl.sdk.gson.GsonUtils;
import com.google.gson.JsonObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.BasicHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;

/**
 * Created by Administrator on 2018/1/7.
 */
public class HttpUtils {

    private static final int readTimeoutMs = 10000;
    private static final int connectTimeoutMs = 10000;

    public static String get(String url) {
        String result = null;
        // 根据地址获取请求
        HttpGet httpGet = new HttpGet(url);
        // 获取当前客户端对象
        HttpClient httpClient = new DefaultHttpClient();
        // 通过请求对象获取响应对象
        try {
            HttpResponse response = httpClient.execute(httpGet);
            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                result = EntityUtils.toString(response.getEntity(), "utf-8");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String post(String url, Map<String, Object> param) {
        String result = null;
        //POST的URL
        HttpPost httppost = new HttpPost(url);
//建立HttpPost对象
        List<NameValuePair> params = new ArrayList<NameValuePair>();
//建立一个NameValuePair数组，用于存储欲传送的参数
        if (null != param) {
            Set<Map.Entry<String, Object>> set = param.entrySet();
            Iterator<Map.Entry<String, Object>> it = set.iterator();
            while (it.hasNext()) {
                Map.Entry<String, Object> entry = it.next();
                //添加参数
                params.add(new BasicNameValuePair(entry.getKey(), entry.getValue().toString()));
            }
        }
        try {
            httppost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
//设置编码
        HttpResponse response = null;
        try {
            response = new DefaultHttpClient().execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
//发送Post,并返回一个HttpResponse对象
        if (response.getStatusLine().getStatusCode() == 200) {//如果状态码为200,就是正常返回
            try {
                result = EntityUtils.toString(response.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }


    public static InputStream postJson(String url, Map<String, Object> param) {
        InputStream is = null;
        //POST的URL
        HttpPost httppost = new HttpPost(url);
        StringEntity entity = new StringEntity(GsonUtils.mapToJson(param), "utf-8");//解决中文乱码问题
        entity.setContentEncoding("UTF-8");
        entity.setContentType("application/json");
        httppost.setEntity(entity);
        HttpResponse response = null;
        try {
            response = new DefaultHttpClient().execute(httppost);
        } catch (IOException e) {
            e.printStackTrace();
        }
//发送Post,并返回一个HttpResponse对象
        if (response.getStatusLine().getStatusCode() == 200) {//如果状态码为200,就是正常返回
            try {
                HttpEntity httpEntity = response.getEntity();
                is = httpEntity.getContent();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return is;
    }

    public static String postXml(String url, String data) {
        String result = null;
        BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
                RegistryBuilder.<ConnectionSocketFactory>create()
                        .register("http", PlainConnectionSocketFactory.getSocketFactory())
                        .register("https", SSLConnectionSocketFactory.getSocketFactory())
                        .build(),
                null,
                null,
                null
        );
        HttpClient httpClient = HttpClientBuilder.create()
                .setConnectionManager(connManager)
                .build();
        //POST的URL
        HttpPost httppost = new HttpPost(url);
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(readTimeoutMs).setConnectTimeout(connectTimeoutMs).build();
        httppost.setConfig(requestConfig);
        StringEntity postEntity = new StringEntity(data, "UTF-8");
        httppost.addHeader("Content-Type", "text/xml");
        httppost.setEntity(postEntity);
        //设置编码
        HttpResponse response = null;
        try

        {
            response = httpClient.execute(httppost);
        } catch (
                IOException e)

        {
            e.printStackTrace();
        }
//发送Post,并返回一个HttpResponse对象
        if (response.getStatusLine().getStatusCode() == 200) {//如果状态码为200,就是正常返回
            try {
                result = EntityUtils.toString(response.getEntity());
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }
}
